package generator.controller.dev;

import generator.domain.*;
import generator.service.*;
import generator.utis.Constants;
import generator.utis.PageSupport;
import generator.utis.UploadUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Description: TODO
 * @author: 李展鹏
 * @date: 2024年05月13日17:01
 */
@Controller
@RequestMapping("/dev")
public class DevUserController {
    @Resource
    private DevUserService devUserService;
    @Resource
    AppInfoService appInfoService;
    @Resource
    AppCategoryService appCategoryService;
    @Resource
    DataDictionaryService dataDictionaryService;

    @Resource
    AppVersionService appVersionService;

    //跳转到开发者登录
    @RequestMapping("/login")
    public String DevUserLogin() {
        return "devlogin";
    }

    //进行开发者登录操作
    @RequestMapping("/devLoginMain")
    public String doDevUserLogin(@RequestParam("devcode") String devCode,
                                 @RequestParam("devpassword") String devPassword,
                                 HttpSession session, HttpServletRequest request) {
        DevUser devUser = devUserService.getDevUserByUsername(devCode);
        if (devUser == null) {
            //用户不存在
            request.setAttribute("error", "用户不存在");
            return "devlogin";
        }
        //如果用户存在接下来就开始验证密码
        if (devUser.getDevpassword().equals(devPassword)) {
            //密码正确，将登录的用户放入Session中
            session.setAttribute("devUserSession", devUser);
            return "redirect:/dev/toMain";
        }
        return "devlogin";
    }

    //跳转到首页
    @RequestMapping("/toMain")
    private String main(HttpSession session) {
        if (session.getAttribute("devUserSession") == null) {
            return "redirect:/dev/login";
        }
        return "developer/main";
    }

    //分页
    @RequestMapping("/list")
    private String DevUser(Model model, @RequestParam(value = "querySoftwareName", required = false) String softwareName,
                           @RequestParam(value = "queryStatus", required = false) Integer status,
                           @RequestParam(value = "queryCategoryLevel1", required = false) Integer categoryLevel1,
                           @RequestParam(value = "queryCategoryLevel2", required = false) Integer categoryLevel2,
                           @RequestParam(value = "queryCategoryLevel3", required = false) Integer categoryLevel3,
                           @RequestParam(value = "queryFlatformId", required = false) Integer flatformId,
                           @RequestParam(required = false) Integer devId,
                           @RequestParam(value = "currentPageNo", required = false, defaultValue = "1") Integer currentPageNo) {
        List<AppInfo> appInfoList = null;
        List<DataDictionary> dataDictionaries = null;
        List<DataDictionary> dataDictionaries1 = null;
        List<generator.domain.AppCategory> appCategorie1 = null;
        List<generator.domain.AppCategory> appCategorie2 = null;
        List<AppCategory> appCategorie3 = null;
        try {
            int pageSize = Constants.pageSize;
            int totalCount = appInfoService.getAppInfoCount(softwareName, status, categoryLevel1, categoryLevel2, categoryLevel3, flatformId, devId);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(currentPageNo);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if (currentPageNo > totalPageCount) {
                currentPageNo = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            appInfoList = appInfoService.getAppInfoList(softwareName, status, categoryLevel1, categoryLevel2, categoryLevel3, flatformId, devId, currentPageNo, pageSize);
            dataDictionaries = dataDictionaryService.getDataDictionaryList();
            dataDictionaries1 = dataDictionaryService.getDataDictionaryStatusList();
            appCategorie1 = appCategoryService.getAppCategory1List(1);
            appCategorie2 = appCategoryService.getAppCategory1List(categoryLevel1);
            appCategorie3 = appCategoryService.getAppCategory1List(categoryLevel2);
            model.addAttribute("appInfoList", appInfoList);
            model.addAttribute("flatFormList", dataDictionaries);
            model.addAttribute("statusList", dataDictionaries1);
            model.addAttribute("categoryLevel1List", appCategorie1);
            model.addAttribute("categoryLevel2List", appCategorie2);
            model.addAttribute("categoryLevel3List", appCategorie3);
            model.addAttribute("querySoftwareName", softwareName);
            model.addAttribute("queryCategoryLevel1", categoryLevel1);
            model.addAttribute("queryCategoryLevel2", categoryLevel2);
            model.addAttribute("queryCategoryLevel3", categoryLevel3);
            model.addAttribute("queryFlatformId", flatformId);
            model.addAttribute("devId", devId);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("currentPageNo", currentPageNo);
            model.addAttribute("queryStatus", status);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "developer/appinfolist";
    }

    @RequestMapping("/toVersion/{appinfoid}")
    public String doAdd(@PathVariable Integer appinfoid, Model model) {
        List<AppVersion> appVersion = appVersionService.getByList(appinfoid);
        model.addAttribute("appVersionList", appVersion);
        model.addAttribute("appId", appinfoid);
        return "developer/appversionadd";
    }

    @RequestMapping("/toDetail/{appinfoid}")
    public String doDetail(@PathVariable Integer appinfoid, Model model) {
        AppInfo appInfo = appInfoService.getByIdAppInfo(appinfoid);
        model.addAttribute("appInfo", appInfo);
        return "developer/appinfoview";
    }

    @RequestMapping("/addVersion")
    public String addVersion(AppVersion appVersion
            , @RequestParam(value = "a_downloadLink") MultipartFile a_downloadLink) {
        System.out.println("==============》》addVersion");
        System.out.println(appVersion);
        boolean result = appVersionService.save(appVersion);
        if (result) {
            return "redirect:/dev/list";
        }
        return "redirect:/dev/toVersion/" + appVersion.getAppid();
    }

    @RequestMapping("/toAppInfoAdd")
    public String doAppInfoAdd(@RequestParam(value = "categorylevel1", required = false) Integer categoryLevel1Name,
                               @RequestParam(value = "categorylevel2", required = false) Integer categoryLevel2Name,
                               @RequestParam(value = "categorylevel3", required = false) Integer categoryLevel3Name
            , @RequestParam(value = "flatformid", required = false) Integer flatformId, Long devId, Model model) {
        List<DataDictionary> dataDictionaries = null;
        List<AppCategory> appCategorie1 = null;
        List<AppCategory> appCategorie2 = null;
        List<AppCategory> appCategorie3 = null;
        dataDictionaries = dataDictionaryService.getDataDictionaryList();
        appCategorie1 = appCategoryService.getAppCategory1List(1);
        appCategorie2 = appCategoryService.getAppCategory1List(categoryLevel1Name);
        appCategorie3 = appCategoryService.getAppCategory1List(categoryLevel2Name);
        model.addAttribute("queryCategoryLevel01", categoryLevel1Name);
        model.addAttribute("queryCategoryLevel02", categoryLevel2Name);
        model.addAttribute("queryCategoryLevel03", categoryLevel3Name);
        model.addAttribute("categoryLevel01List", appCategorie1);
        model.addAttribute("categoryLevel02List", appCategorie2);
        model.addAttribute("categoryLevel03List", appCategorie3);
        model.addAttribute("flatFormList1", dataDictionaries);
        model.addAttribute("queryFlatformId1", flatformId);
        return "developer/appinfoadd";
    }

    @PostMapping("/appinfoadd")
    public String appInfoAdd(AppInfo appInfo, HttpSession session, HttpServletRequest request, @RequestParam(value = "a_logoPicPath") MultipartFile attach) throws IOException {
        String logoPicPath = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "files");
            String oIdFileName = attach.getOriginalFilename();   //原文件名
            String suffix = FilenameUtils.getExtension(oIdFileName);  //原文件后缀
            int filesize = 5000000;
            if (attach.getSize() > filesize) {
                request.setAttribute("uploadFileError", "* 上传大小不得超过500KB");
            } else if (suffix.equalsIgnoreCase("jpg")
                    || suffix.equalsIgnoreCase("png")
                    || suffix.equalsIgnoreCase("jpeg")
                    || suffix.equalsIgnoreCase("pneg")) {
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                File targetFile = new File(path);
                if (!targetFile.exists()) {

                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(new File(targetFile, fileName));
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "* 上传文件失败!");
                }
                logoPicPath = File.separator + "statics" + File.separator + "files" + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", "* 上传图片格式不正确");
            }
        }
        System.out.println(appInfo);
        DevUser devUserSession = (DevUser) session.getAttribute("devUserSession");
        System.out.println(devUserSession.getId()+"fdsdfdfds");
        appInfo.setCreatedby(devUserSession.getId());
        appInfo.setDevid(((DevUser) session.getAttribute("devUserSession")).getId());
        appInfo.setLogopicpath(logoPicPath);
//       sysUser.setWorkpicpath();
        if (appInfoService.save(appInfo)) {
            UploadUtil.uploadImage(attach);
            return "redirect:/dev/list";
        } else {
            return "redirect:/dev/toAppInfoAdd";
        }
    }
}
